package com.zt.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zt.reggie.common.R;
import com.zt.reggie.entity.Category;
import com.zt.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 挚爱之夕
 * @version 1.0
 * @implSpec com.zt.reggie.controller
 * @since 2023 - 02 - 25 - 14:43
 */
@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    //保存菜品分类
    @PostMapping
    public R<String> save(@RequestBody Category category){
        log.info("category:{}", category);
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    //分页查询
    @GetMapping("/page")
    public R<Page<Category>> page(Integer page, Integer pageSize){
        //分页构造器
        Page<Category> pageInfo = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //按sort 升序排
        wrapper.orderByAsc(Category::getSort);

        categoryService.page(pageInfo, wrapper);

        return R.success(pageInfo);
    }

    //删除菜品分类
    @DeleteMapping
    public R<String> delete(Long ids){
        log.info("删除分类,id={}", ids);
//        categoryService.removeById(ids);
        //自定义 删除前检查分类是否关联套餐 或 菜品
        categoryService.remove(ids);

        return R.success("分类信息删除成功");
    }

    //修改菜品分类
    @PutMapping
    public R<String> update(@RequestBody Category category){
        log.info("修改分类:{}", category);

        categoryService.updateById(category);
        return R.success("修改分类信息成功!");
    }

    //根据 type 查询分类， 用于菜单管理的新建菜品 的下拉列表显示 和 套餐管理的新增套餐 的下拉列表显示
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        //条件构造器
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();

        //条件
        wrapper.eq(category.getType() != null, Category::getType, category.getType());
        //根据sort 升序， updateTime 降序
        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(wrapper);
        return R.success(list);
    }


}
